/* 
 * cms，一个基于J2EE架构内容管理系统
 * Copyright © GrayRabbit Co., Ltd. All rights reserved.
 * Department:运营department
 * 更多信息请访问：
 * http://code.google.com/p/gray-rabbit-cms/
 */
package org.grayrabbit.cms.action.component;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.grayrabbit.cms.action.common.SimpleAction;
import org.grayrabbit.cms.constant.ConstantWebApp;
import org.grayrabbit.cms.constant.DictionaryStaticValues;
import org.grayrabbit.cms.entity.Category;
import org.grayrabbit.cms.entity.Site;
import org.grayrabbit.cms.entity.Topic;
import org.grayrabbit.cms.service.category.CategoryService;
import org.grayrabbit.cms.service.site.SiteService;
import org.grayrabbit.cms.service.topic.TopicService;
import org.grayrabbit.cms.util.ComponentUtil;
import org.grayrabbit.cms.vo.category.CategoryBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;


/**

 * @version 1.0,创建时间:2011-05-16 15:57:47
 */
@Controller
@Scope("prototype")
@Results({
		@Result(name="success", type="dispatcher", location="componentpage.jsp")
})
public class ComponentAction extends SimpleAction {

	private static final long serialVersionUID = 1L;
	private static final String SPT =File.separator;
	private static final String SUFFIX =".tpl";
	private static final String CATFRAME = "catframe";
	
	//组件文件路径
	private static final String PATH_PREFIX =SPT+"theme"+SPT+"component"+SPT;
	private static final String PATH_ROLL_ANNOUNCE=PATH_PREFIX+ComponentUtil.TYPE_ROLL_ANNOUNCE+SUFFIX;
	private static final String PATH_ROTATE=PATH_PREFIX+ComponentUtil.TYPE_ROTATE+SUFFIX;
	private static final String PATH_ASSOCIATION_DOC=PATH_PREFIX+ComponentUtil.TYPE_ASSOCIATION_DOC+SUFFIX;
	private static final String PATH_PAGINATION = PATH_PREFIX+ComponentUtil.TYPE_PAGINATION+SUFFIX;
	private static final String PATH_SITE_CAT_NAV = PATH_PREFIX+ComponentUtil.TYPE_SITECATNAV+SUFFIX;
	private static final String PATH_CATFRAME = PATH_PREFIX+CATFRAME+SUFFIX;
	private static final String PATH_CRUMBS = PATH_PREFIX+ComponentUtil.TYPE_CRUMBS+SUFFIX;
	private static final String PATH_LEFTTREE = PATH_PREFIX+ComponentUtil.TYPE_LEFTTREE+SUFFIX;
	
	private static String CONTENT_PATH = null;
	private Logger LOG = LoggerFactory.getLogger(ComponentAction.class);
	@Autowired
	@Qualifier("siteServiceImpl")
	private SiteService siteService;
	
	@Autowired
	@Qualifier("topicServiceImpl")
	private TopicService topicService;
	
	@Autowired
	@Qualifier("categoryServiceImpl")
	private CategoryService categoryService;

	private Site site;
	private String component;
	private String componentType;
	private String catIds;
	private String parameters;
	private List<Topic> topicList = new ArrayList<Topic>();
	private List<Category> catList = new ArrayList<Category>();
	private CategoryBean categoryBean;

	@Action(value = "componentpage")
	public String loadComponentPage() {
		try {
			if(StringUtils.isNotBlank(componentType)){
				if(ComponentUtil.TYPE_ROLL_ANNOUNCE.equalsIgnoreCase(componentType)){
					loadSiteTree(); 
					loadComponentFile(getContextpath()+PATH_ROLL_ANNOUNCE);					
				}else if (ComponentUtil.TYPE_ROTATE.equalsIgnoreCase(componentType)){
					loadSiteTree(); 
					loadTopicList();
					loadComponentFile(getContextpath()+PATH_ROTATE);
				}else if(ComponentUtil.TYPE_ASSOCIATION.equalsIgnoreCase(componentType)) {
					loadSiteTree();
					loadComponentFile(getContextpath()+PATH_ASSOCIATION_DOC);
				}else if(ComponentUtil.TYPE_PAGINATION.equalsIgnoreCase(componentType)) {
					loadComponentFile(getContextpath()+PATH_PAGINATION);
				}else if(ComponentUtil.TYPE_SITE_CAT_NAV.equalsIgnoreCase(componentType)) {
					loadSiteTree();
					loadComponentFile(getContextpath()+PATH_SITE_CAT_NAV);
				}else if(ComponentUtil.TYPE_CATEFRAME.equalsIgnoreCase(componentType)) {
					loadSiteTree();
					loadComponentFile(getContextpath()+PATH_CATFRAME);
				}else if(ComponentUtil.TYPE_CRUMBS.equalsIgnoreCase(componentType)) {
					loadSiteTree();
					loadComponentFile(getContextpath() + PATH_CRUMBS); 
				}else if(ComponentUtil.TYPE_LEFTTREE.equalsIgnoreCase(componentType)) {
					loadSiteTree();
					loadComponentFile(getContextpath() + PATH_LEFTTREE);
				}
			}
		} catch (IOException e) {
			LOG.error("组件加载异常", e);
			e.printStackTrace();
		}
		return SUCCESS;
	}
	
	
	@Action(value="loadcomponent")
	public String loadcomponent(){
		try {
			if(StringUtils.isBlank(componentType)) 
				return renderHtml("<p>组件类型错误为空</p>");
			String path = getComponentPath(componentType);
			component = loadComponentFile(getContextpath()+path);
			if(StringUtils.isBlank(component))
				return renderHtml("<p>组件内容为空</p>");
			else  
				return renderHtml("<p>"+component+"</p>");
		} catch (IOException e) {
			e.printStackTrace();
			LOG.error("组件文件读取异常", e);
			return renderHtml("<p>组件类型错误为空</p>");
		} 
	}

	/**  依据组件类型 进行扩展
	 * @param componentType
	 * @return
	 */
	private String getComponentPath(String componentType){
		 if(ComponentUtil.TYPE_ROLL_ANNOUNCE.equalsIgnoreCase(componentType)){
			 return PATH_ROLL_ANNOUNCE;
		 }else if(ComponentUtil.TYPE_ROTATE.equalsIgnoreCase(componentType)){
			 return PATH_ROTATE;
		 }else if(ComponentUtil.TYPE_ASSOCIATION.equalsIgnoreCase(componentType)){
			 return PATH_ASSOCIATION_DOC;
		 }else if(ComponentUtil.TYPE_PAGINATION.equalsIgnoreCase(componentType)) {
			 return PATH_PAGINATION;
		 }else if(ComponentUtil.TYPE_SITE_CAT_NAV.equalsIgnoreCase(componentType)) {
			 return PATH_SITE_CAT_NAV;
		 }else if(ComponentUtil.TYPE_CATEFRAME.equalsIgnoreCase(componentType)) {
			 return PATH_CATFRAME;
		 }else if(ComponentUtil.TYPE_CRUMBS.equalsIgnoreCase(componentType)) {
			 return PATH_CRUMBS;
		 }else if(ComponentUtil.TYPE_LEFTTREE.equalsIgnoreCase(componentType)){
			 return PATH_LEFTTREE;
		 }
		 else{
			 return null;
		 }
		 
	}
	
	private String loadComponentFile(String filePath) throws IOException{
		String path = null;
		if(StringUtils.isBlank(filePath)) return component;
		if(componentType.equalsIgnoreCase(ComponentUtil.TYPE_ROLL_ANNOUNCE)) {
			path = getContextpath()+PATH_ROLL_ANNOUNCE;
		}else if(componentType.equalsIgnoreCase(ComponentUtil.TYPE_ROTATE)) {
			path = getContextpath() + PATH_ROTATE;
		}else if(componentType.equalsIgnoreCase(ComponentUtil.TYPE_ASSOCIATION)) {
			path = getContextpath() + PATH_ASSOCIATION_DOC;
		}else if(componentType.equalsIgnoreCase(ComponentUtil.TYPE_PAGINATION)) {
			path = getContextpath() + PATH_PAGINATION;
		}else if(componentType.equalsIgnoreCase(ComponentUtil.TYPE_SITE_CAT_NAV)) {
			path = getContextpath() + PATH_SITE_CAT_NAV;
		}else if(componentType.equalsIgnoreCase(ComponentUtil.TYPE_CATEFRAME)) {
			path = getContextpath() + PATH_CATFRAME;
		}else if(componentType.equalsIgnoreCase(ComponentUtil.TYPE_CRUMBS)) {
			path = getContextpath() + PATH_CRUMBS;
		}else if(componentType.equalsIgnoreCase(ComponentUtil.TYPE_LEFTTREE)) {
			path = getContextpath() + PATH_LEFTTREE;
		}
		File file = new File(path);
		if(!file.exists() || !file.isFile()) return component;
		component = FileUtils.readFileToString(file, "utf-8");
		if(componentType.equalsIgnoreCase("pagination")) {
			return component;
		}
		return ComponentUtil.componentLoadParameters(component, componentType,parameters);
		 
	}
	private String getContextpath(){
		if(StringUtils.isBlank(CONTENT_PATH)){
			CONTENT_PATH = ServletActionContext.getServletContext().getRealPath("/"); 
		} 
		return  CONTENT_PATH;
	}
		
	private void loadSiteTree() {
		Site currentSite = (Site)getSessionValue(ConstantWebApp.CURRENT_SITE);
		if(currentSite == null || StringUtils.isBlank(currentSite.getSiteId()))
			return ;
		site = siteService.getSiteWithAllCategory(currentSite.getSiteId());
	}
	
	/**
	 *  当前站点下的所有的可发布的专题（启用状态  并且通过审核或者已经发布过）；
	 */
	private void loadTopicList(){
		Site currentSite = (Site)getSessionValue(ConstantWebApp.CURRENT_SITE);
		if(currentSite == null || StringUtils.isBlank(currentSite.getSiteId()))
			return ;
		List<Topic> list = topicService.findBySiteId(currentSite.getSiteId());
		if(list == null || list.isEmpty())  return;
		for(Topic t :list){
			if(t.getIsEnable()!=null && t.getIsEnable()  
					&& (DictionaryStaticValues.TOPIC_STATUS_SUCCESS.equals(t.getTopicStatus())
					  || DictionaryStaticValues.TOPIC_STATUS_PUBLISH.equals(t.getTopicStatus()))){
				topicList.add(t);					
			}
		}		
	}
	protected void loadCategoryList() {
		Site currentSite = (Site)getSessionValue(ConstantWebApp.CURRENT_SITE);
		if(currentSite == null || StringUtils.isBlank(currentSite.getSiteId()))
			return ;
		List<Category> list = categoryService.allCatList(currentSite.getSiteId());
		if(list == null || list.isEmpty()) return;
		for(Category cat : list) {
			catList.add(cat);
		}
	}

	public Site getSite() {
		return site;
	}

	public void setSite(Site site) {
		this.site = site;
	}

	public String getComponent() {
		return component;
	}

	public void setComponent(String component) {
		this.component = component;
	}

	public String getComponentType() {
		return componentType;
	}

	public void setComponentType(String componentType) {
		this.componentType = componentType;
	}


	public String getCatIds() {
		return catIds;
	}


	public void setCatIds(String catIds) {
		this.catIds = catIds;
	}


	public String getParameters() {
		return parameters;
	}


	public void setParameters(String parameters) {
		this.parameters = parameters;
	}


	public List<Topic> getTopicList() {
		return topicList;
	}


	public void setTopicList(List<Topic> topicList) {
		this.topicList = topicList;
	}


	public List<Category> getCatList() {
		return catList;
	}


	public void setCatList(List<Category> catList) {
		this.catList = catList;
	}


	public CategoryBean getCategoryBean() {
		return categoryBean;
	}


	public void setCategoryBean(CategoryBean categoryBean) {
		this.categoryBean = categoryBean;
	}

}
